// generator 的用法，类似同步的写法

const fs = require('fs').promises;

function* read() {
  let name = yield fs.readFile('./code/name.txt', 'utf8');
  let age = yield fs.readFile('./code/' + name, 'utf8');
  return age;
}

const it = read();

/* const { value, done } = it.next();

value.then((res) => {
  console.log(res);
  const { value1, done1 } = it.next(res);
  value1.then((data) => {
    console.log(data);
  });
}); */

function co(it) {
  return new Promise(function (resolve, reject) {
    function step(data) {
      let { value, done } = it.next(data);
      if (!done) {
        Promise.resolve(value).then(
          (res) => {
            step(res);
          },
          (err) => {
            reject(err);
          }
        );
      } else {
        resolve(value);
      }
    }
    step();
  });
}

co(read())
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });
